<template>
  <div class="content-wrapper">
    <div class="content-container">
      <el-form :inline="true" :model="listQuery" class="filter-container">
        <el-form-item label="设备分类">
          <el-select
            v-model="listQuery.category"
            size="mini"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="listQuery.status"
            size="mini"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="搜索条件">
          <el-select
            v-model="listQuery.keywordField"
            size="mini"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="item in conditionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input
            v-model="listQuery.keyword"
            size="mini"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            class="filter-item"
            size="small"
            round
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button
            class="filter-item"
            size="small"
            round
            icon="el-icon-plus"
            @click="openCreateDialog()"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="listLoading" :data="dataList" highlight-current-row>
        <el-table-column label="状态" prop="status" width="60px">
          <template slot-scope="{ row }">
            {{ formatByKeyValue(statusOptions, row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="设备编号" prop="equipmentCode" width="160px" />
        <el-table-column
          label="设备名称"
          prop="equipmentName"
          min-width="100px"
        />
        <el-table-column label="分类" width="100px">
          <template slot-scope="{ row }">
            {{ formatByKeyValue(categoryOptions, row.category) }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" prop="brand" width="100px" />
        <el-table-column label="型号" prop="model" width="100px" />
        <el-table-column
          label="规格"
          prop="specification"
          width="160px"
          align="center"
        />
        <el-table-column label="有效期" prop="expirationDate" width="160px" />
        <el-table-column label="维护周期" width="160px">
          <template slot-scope="{ row }">
            <span v-if="row.maintainPeriodType !== 0">
              {{ row.maintainPeriod }}
            </span>
            {{
              formatByKeyValue(
                maintainPeriodTypeOptions,
                row.maintainPeriodType
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="维保联系人"
          prop="maintainContact"
          width="100px"
        />
        <el-table-column label="联系电话" prop="maintainTel" width="100px" />
        <el-table-column label="地点" prop="equipmentCode" width="100px" />
        <el-table-column
          label="所属部门"
          prop="userGroupId"
          :formatter="groupConvert"
          width="100px"
        />
        <el-table-column label="备注" prop="memo" min-width="100px" />
        <el-table-column label="创建人" prop="createUserName" width="100px" />
        <el-table-column label="更新人" prop="updateUserName" width="100px" />
        <el-table-column label="更新时间" prop="updateTime" width="160px" />
        <el-table-column label="操作" align="center" width="80px" fixed="right">
          <template slot-scope="{ row }">
            <el-dropdown trigger="click" class="filter-item">
              <el-button type="text" class="el-icon-more" />
              <el-dropdown-menu slot="dropdown" class="user-dropdown">
                <el-dropdown-item @click.native="updateStatus(row)">{{
                  !row.status == 1 ? '启用' : '停用'
                }}</el-dropdown-item>
                <el-dropdown-item @click.native="openEditDialog(row)">
                  编辑
                </el-dropdown-item>                <el-dropdown-item @click.native="copyCreateDialog(row)">
                  复制
                </el-dropdown-item>
                <el-dropdown-item @click.native="deleteEquipment(row)">
                  删除
                </el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page-number.sync="listQuery.pageNumber"
        :page-size.sync="listQuery.pageSize"
        @pagination="getList"
      />
      <Save
        :visible.sync="dialogVisible"
        :dialog-status="dialogStatus"
        :category-options="categoryOptions"
        :current-row="currentRow"
        :scope="scope"
        @saveData="handleSaveData"
      />
    </div>
  </div>
</template>

<script>
import {
  pageEquipment,
  updateEquipmentStatus,
  deleteEquipment,
  listPreOptions
} from '@/api/base/equipment'
import { formatByKeyValue } from '@/utils'
import { fromBase64X } from '@/utils/string-util'
import Pagination from '@/components/Pagination'
import Save from './components/save'
import { listUserGroupTreeItemForManage } from '@/api/uc/userGroup'

export default {
  components: {
    Pagination,
    Save
  },
  data() {
    return {
      scope: fromBase64X(this.$route.params.scope, 1),
      statusOptions: null,
      categoryOptions: null,
      conditionOptions: [
        { value: 'equipmentCode', label: '设备编号' },
        { value: 'equipmentName', label: '设备名称' }
      ],
      listLoading: false,
      dataList: [],
      total: 0,
      listQuery: {
        pageNumber: 1,
        pageIndex: 0,
        pageSize: 5,
        scope: fromBase64X(this.$route.params.scope, 1)
      },
      currentRow: null,
      dialogVisible: false,
      dialogStatus: null,
      groupData: [],
      maintainPeriodTypeOptions: [
        { key: 0, value: '按需' },
        { key: 1, value: '天' },
        { key: 2, value: '周' },
        { key: 3, value: '月' },
        { key: 4, value: '年' }
      ]
    }
  },
  mounted() {
    // console.log(fromBase64X(this.$route.params.scope, 1), 'scope')
    // 获取组织架构
    this.getGroupTree()

    listPreOptions().then((res) => {
      const data = res.data
      this.statusOptions = data.status
      this.categoryOptions = data.equipmentCategory
      this.getList()
    })
  },
  methods: {
    groupConvert(row, column, cellValue) {
      const group = this.groupData.find((e) => e.id === cellValue)
      return group ? group.name : ''
    },
    async getGroupTree() {
      await listUserGroupTreeItemForManage({ parentUserGroupId: null }).then(
        (res) => {
          this.groupTree = res.data
          this.getGroupNames(res.data, 0)
        }
      )
    },
    getGroupNames(data, parentId) {
      for (let i = 0; i < data.length; i++) {
        this.groupData.push({
          id: data[i].value,
          name: data[i].label,
          parentId: parentId
        })
        if (data[i].children != null && data[i].children !== undefined) {
          this.getGroupNames(data[i].children, data[i].value)
        }
      }
    },
    getGroupNameIds(id) {
      const parentData = this.groupData.find((e) => e.id === id)
      var ids = []
      ids.unshift(id)
      this.getParentId(parentData.parentId, ids)
      return ids
    },
    getParentId(parentId, ids) {
      if (parentId === 0) {
        return
      }
      const parentData = this.groupData.find((e) => e.id === parentId)
      ids.unshift(parentData.id)
      this.getParentId(parentData.parentId, ids)
    },
    formatByKeyValue,
    getList() {
      this.listQuery.pageIndex = this.listQuery.pageNumber - 1
      pageEquipment(this.listQuery).then((res) => {
        this.dataList = res.data.rows
        this.total = res.data.total
      })
    },
    search() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    openCreateDialog() {
      this.dialogVisible = true
      this.dialogStatus = 'create'
    },
    copyCreateDialog(row) {
      // 引用修改的那些逻辑
      this.currentRow = {}
      this.currentRow = Object.assign({}, row)
      this.currentRow.userGroupId = this.getGroupNameIds(row.userGroupId)
      this.currentRow.equipmentId = null
      console.log(this.currentRow, 'this.currentRow')
      // 打开新增视图
      this.dialogVisible = true
      this.dialogStatus = 'create'
    },
    openEditDialog(row) {
      this.currentRow = {}
      this.currentRow = Object.assign({}, row)
      this.currentRow.userGroupId = this.getGroupNameIds(row.userGroupId)
      console.log(this.currentRow, 'this.currentRow')
      this.dialogVisible = true
      this.dialogStatus = 'update'
    },
    handleSaveData(data) {
      if (this.dialogStatus === 'create') {
        this.search()
      } else {
        const index = this.list.findIndex((v) => v.goodsId === data.goodsId)
        this.list.splice(index, 1, data)
      }
    },
    deleteEquipment(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteEquipment(row).then((res) => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    updateStatus(row) {
      row.status = row.status === 1 ? 2 : 1
      updateEquipmentStatus(row)
        .then((res) => {
          this.getList()
          this.$message.success(row.status === 1 ? '启用成功' : '禁用成功')
        })
        .catch((res) => {
          row.status = row.status === 1 ? 2 : 1
        })
    }
  }
}
</script>
